<?php
namespace app\common\service;;

use app\common\logic\CartLogic;
use app\common\logic\FreightLogic;
use think\facade\Db;

class Orders extends Base {

    //订单确认
    public function preview(){
        $user_id = $this->user_id;
        $cart_ids = input('cart_ids');
        $goods_id = input('goods_id');
        $goods_num = input('goods_num')?:1;
        $action = input("action/s"); // 行为
        $coupon_ids = input('couponrids')?:'';
        $coupon_ids = json_decode($coupon_ids,true);
        if(!is_array($coupon_ids)){
            $coupon_ids = [];
        }
        $cuxiaoids = input('cuxiaoids');
        $cuxiaoids = json_decode($cuxiaoids,true);
        if(!is_array($cuxiaoids)){
            $cuxiaoids = [];
        }
        $use_score = input('use_score')?:0;
        if($cart_ids){
            $cart_id_arr = explode(',',$cart_ids);
            Db::name('cart')->where(['user_id'=>$this->user_id])->update(['selected'=>0]);
            Db::name('cart')->where('user_id',$this->user_id)->where('id','in',$cart_id_arr)->update(['selected'=>1]);
            $cart_list = Db::name('cart')->where('id','in',$cart_id_arr)->field('goods_id,goods_num')->select();
            $data = [];
            $action = '';
        }else{
            $prodata = input('prodata');
            $prodata = explode(',',$prodata);
            $data = [
                'user_id' => $user_id,
                'goods_id' => $prodata[0],
                'item_id' => $prodata[1],
                'goods_num' => $prodata[2],
            ];
            $action = 'buy_now';
        }

        $address_id = input('address_id/d');
        if($address_id){
            $address = Db::name('user_address')->where("address_id", $address_id)->find();
            $area = Db::name('region')->column('name','id');
            $address['province_name'] = $area[$address['province']];
            $address['city_name'] = $area[$address['city']];
            $address['district_name'] = $area[$address['district']];
            $address['area'] = $address['province_name'].','.$address['city_name'].','.$address['district_name'];
        } else {
            $address = Db::name('user_address')->where(['user_id'=>$this->user_id])->order(['is_default'=>1])->find();
            if($address){
                $area = Db::name('region')->column('name','id');
                $address['province_name'] = $area[$address['province']];
                $address['city_name'] = $area[$address['city']];
                $address['district_name'] = $area[$address['district']];
                $address['area'] = $address['province_name'].','.$address['city_name'].','.$address['district_name'];
            }
        }

        $cartLogic = new CartLogic($data);

        $cartLogic->setUserId($this->user_id);
        //立即购买
        if($action == 'buy_now'){
            $buyGoods = $cartLogic->buyPreview();
            if(isset($buyGoods['status']) && $buyGoods['status']!=1){
                $result = [
                    'status' => false,
                    'msg' => $buyGoods['msg'],
                    'data' => []
                ];
                return $result;
            }
            $cartList = $buyGoods;
        }else{
            if ($cartLogic->getUserCartOrderCount() == 0){
                $result = [
                    'status' => false,
                    'msg' => '你的购物车没有选中商品',
                    'data' => []
                ];
                return $result;
            }
            $cartList = $cartLogic->getCartList(1); // 获取用户选中的购物车商品
        }
        if(isset($cartList['status']) && $cartList['status']==0){
            $this->error($cartList['msg']);
        }
        //$cartList = array_values($cartList);

        $cartPriceInfo = $cartLogic->getCartPriceInfo($cartList,$coupon_ids,$use_score,$cuxiaoids);  //初始化数据。商品总额/节约金额/商品总共数量

        //dump($cartList);exit;
        //运费
        $region_id = $address['city']??'';
        $special_region = Db::name('region')->where('(name like "%天津%") or (name like "%北京%") or (name like "%上海%") or (name like "%重庆%")')->column('id');
        if($address && in_array($address['province'],$special_region)){
            $region_id = $address['district']??'';
        }
        $freight = logic('GoodsLogic')->getFreight( $cartList,$region_id);

        $freightLogic = new FreightLogic();
        $pay_score_total = 0;
        $score_money_total = 0;
        foreach($cartList as $suid =>$sval){
            $goodsArr = $sval['goods'];
            $goods_ids = get_arr_column($goodsArr, 'goods_id');
            //获取运费模板
            $goodsList = Db::name('Goods')->where('goods_id', 'IN', $goods_ids)->column('goods_id,template_id,is_free_shipping,cat_id','goods_id');
            foreach ($goodsArr as $cartKey => $cartVal) {
                $goodsArr[$cartKey]['template_id'] = $goodsList[$cartVal['goods_id']]['template_id'];
                $goodsArr[$cartKey]['is_free_shipping'] = $goodsList[$cartVal['goods_id']]['is_free_shipping'];
            }
            $template_list = [];
            foreach ($goodsArr as $goodsKey => $goodsVal) {
                $template_list[$goodsVal['template_id']][] = $goodsVal;
            }
            $total_freight = 0;
            $temp = [];
            $temp['total_weight'] = 0;
            $temp['goods_num'] = 0;
            $temp['is_free_shipping'] = 0;
            foreach ($template_list as $templateVal => $goodsArr) {
                $temp['template_id'] = $templateVal;
                foreach ($goodsArr as $goodsKey => $goodsVal) {
                    $temp['total_weight'] += $goodsVal['weight'] * $goodsVal['goods_num'];
                    $temp['goods_num'] += $goodsVal['goods_num'];
                    $temp['is_free_shipping'] = $goodsVal['is_free_shipping'];
                }
            }
            //配送方式
            $freightList =logic('FreightLogic')->getList([['status','=',1],['sid','=',$suid]]);
            $cartList[$suid]['freightList'] = $freightList;
            $cartList[$suid]['freightkey'] = 0;
            $freight_id = $freightList[0]['template_id'];
            $res_freight = $freightLogic->doCalculation($freight_id,$address,$temp['product_price'],$temp['goods_num'],$temp['total_weight']);
            if($res_freight['status']==0){
                return $res_freight;
            }else{
                $total_freight = $res_freight['freight_price'];
            }
            $cartList[$suid]['total_freight'] = $total_freight;
            //优惠券
            $res_couponList = logic('Coupon')->getUserCouponList($user_id,$suid);
            $couponList = $res_couponList['couponList']??[];
            $coupons = [];
            if(!empty($coupon_ids[$suid])){
                $coupons = Db::name('coupon_record')->where('user_id',$user_id)->where('id','in',$coupon_ids[$suid])->select()->toArray();
            }
            $cartList[$suid]['couponCount'] = count($couponList);//所有优惠券数量
            $cartList[$suid]['couponList'] = $couponList;//所有优惠券
            $cartList[$suid]['coupons'] = $coupons;//已选择的优惠券
            $cartList[$suid]['couponrids'] = $coupon_ids;//已选择的优惠券id
            $cartList[$suid]['sid'] = $suid;
            $cartList[$suid]['coupon_peruselimit'] = 1;//优惠券限用数量

            //促销获得
            $newcxlist = logic('OrderLogic')->get_cuxiao($user_id,$cartList,$cartPriceInfo);
            $cartList[$suid]['cuxiaolist'] = $newcxlist;
            $cartList[$suid]['cuxiaoCount'] = count($newcxlist);
            $cartList[$suid]['cuxiao_money'] = 0;

            $pay_score_total = bcadd($pay_score_total,$sval['pay_score'],2);
            $score_money_total = bcadd($score_money_total,$sval['score_money'],2);
        }

        $userinfo = Db::name('users')->where('user_id',$this->user_id)->find();
        $userinfo['pay_score'] = $pay_score_total;
        $userinfo['score_money'] = $score_money_total;
        $wallet = Db::name('wallet')->where('user_id',$this->user_id)->find();
        $score_to_money = tpCache('shop.score_to_money');//每积分可抵扣
        $score_max_bili = tpCache('shop.score_max_bili');//积分抵扣订单比例
        $userinfo['score'] = $wallet['score'];
        $userinfo['can_use_score'] = $score_to_money>0?1:0;

        $result = [
            'status' => true,
            'msg' => '',
            'data' => [
                'cartPriceInfo' => $cartPriceInfo,
                'address' => $address??'',
                'cartList' => $cartList,
                'freight' => array_sum($freight),
                'userinfo' => $userinfo
            ]
        ];
        return $result;
    }

    //创建订单
    public function createOrder(){
        $address_id = input('address_id')?:0;
        $user_note = input('user_note')?:'';
        $cart_ids = input('cart_ids');
        //优惠券信息
        $coupon_ids = input('couponrids')?:'';
        $coupon_ids = json_decode($coupon_ids,true);
        if(!is_array($coupon_ids)){
            $coupon_ids = [];
        }
        //配送方式
        $freight_ids = input('freightkeys')?:'';
        $freight_ids = json_decode($freight_ids,true);
        if(!is_array($freight_ids)){
            $freight_ids = [];
        }
        //促销活动
        $cuxiaoids = input('cuxiaoids')?:'';
        $cuxiaoids = json_decode($cuxiaoids,true);
        if(!is_array($cuxiaoids)){
            $cuxiaoids = [];
        }
        $use_score = input('use_score')?:0;
        if($cart_ids){
            //加入购物车之后购买的
            $data = [
                'address_id' => $address_id,
                'user_note' => $user_note,
                'couponrids' => $coupon_ids,
                'use_score' => $use_score,
                'freight_ids' => $freight_ids,
                'cuxiaoids' => $cuxiaoids
            ];
        }else{
            //产品详情立即购买的，这种只有一个产品不用考虑多产品的清空
            $prodata = input('prodata');
            $prodata = explode(',',$prodata);
            $data = [
                'user_id' => $this->user_id,
                'goods_id' => $prodata[0],
                'item_id' => $prodata[1],
                'goods_num' => $prodata[2],
                'address_id' => $address_id,
                'user_note' => $user_note,
                'couponrids' => $coupon_ids,
                'use_score' => $use_score,
                'freight_ids' => $freight_ids,
                'cuxiaoids' => $cuxiaoids
            ];
            $action = 'buy_now';
        }
        $cartLogic = new CartLogic($data);
        $cartLogic->setUserId($this->user_id);
        //获取数据
        if($cart_ids){
            if ($cartLogic->getUserCartOrderCount() == 0){
                $result = [
                    'status' => false,
                    'msg' => '你的购物车没有选中商品',
                    'data' => []
                ];
                return $result;
            }
            $buyGoods = $cartLogic->getCartList(1); // 获取用户选中的购物车商品
        }else{

            $buyGoods = $cartLogic->buyNow();
        }
        if(isset($buyGoods['status']) && $buyGoods['status']!=1){
            $result = [
                'status' => false,
                'msg' => $buyGoods['msg'],
                'data' => true
            ];
            return $result;
        }
        $cartList = $buyGoods;


        //提交订单
        $data['user_id'] = $this->user_id;
        $data['username'] = $this->user['username'];


        Db::startTrans();
        $cartPriceInfo = $cartLogic->getCartPriceInfo($cartList,$coupon_ids,$use_score,$cuxiaoids);  //初始化数据。商品总额/节约金额/商品总共数量
        $rs = logic('OrderLogic')->add($cartList,$data);

        if($rs['status']!=1){
            Db::rollback();
            $result = [
                'status' => false,
                'msg' => $rs['msg'],
                'data' => true
            ];
            return $result;
        }


        //回填免费给一单，这里如果是多商家，需要重写
        $id =$rs['result'];
        $order = Db::name('order')->where(['order_id'=>$id])->find();
        if(!$order){
            Db::rollback();
            $result = [
                'status' => false,
                'msg' => '查询订单失败',
                'data' => true
            ];
            return $result;
        }

        Db::commit();
        //清空购物车
        $cartLogic->clear();

        $result = [
            'status' => true,
            'msg' => '创建订单成功！',
            'data' => [
                'order_id' => $id,
                'pay_price' => $order['total_shop_price'],
            ]
        ];
        return $result;
    }
    //商品海报
    function getposter(){
        $post = input();
        //$platform = platform;
        $platform = input('platform')?:'wx';
        $page = '/pages/shop/product';
        $scene = 'id_'.$post['proid'].'-pid_'.$this->user_id;
        $posterset = Db::name('admin_set_poster')->where('type','product')->where('platform',$platform)->order('id')->find();
        $domain_url = getCurUrl();
        if(!$posterset){
            $posterset = [];
            $posterset['type'] = 'product';
            $posterset['platform'] = $platform;
            $posterset['createtime'] = time();
            $posterset['content'] = jsonEncode([
                'poster_bg' => $domain_url.'/static/img/posterbg.jpg',
                'poster_data' => [
                    ['left' => '30px','top' => '70px','type' => 'pro_img','width' => '285px','height' => '285px'],
                    ['left' => '30px','top' => '370px','type' => 'textarea','width' => '286px','height' => '47px','size' => '16px','color' => '#000','content' => '[商品名称]'],
                    ['left' => '34px','top' => '452px','type' => 'head','width' => '47px','height' => '47px','radius' => '100'],
                    ['left' => '89px','top' => '459px','type' => 'text','width' => '50px','height' => '18px','size' => '16px','color' => '#333333','content' => '[昵称]'],
                    ['left' => '90px','top' => '484px','type' => 'text','width' => '98px','height' => '14px','size' => '12px','color' => '#B6B6B6','content' => '推荐给你一个宝贝'],
                    ['left' => '35px','top' => '516px','type' => 'text','width' => '142px','height' => '22px','size' => '20px','color' => '#FD0000','content' => '￥[商品销售价]'],
                    ['left' => '125px','top' => '518px','type' => 'text','width' => '135px','height' => '16px','size' => '14px','color' => '#BBBBBB','content' => '原价:￥[商品市场价]'],
                    ['left' => '221px','top' => '446px','type' => 'qrmp','width' => '94px','height' => '94px','size' => '',],
                ]
            ]);
            $posterset['guize'] = "";
            $poster_id = Db::name('admin_set_poster')->insertGetId($posterset);
        }else{
            $poster_id = $posterset['id'];
        }
        //关闭缓存
        $domain = getCurUrl();
        $user = Db::name('users')->where('user_id',$this->user_id)->find();

        $product = Db::name('goods')->where('goods_id',$post['proid'])->find();
        $domain_url = getCurUrl();
        $textReplaceArr = [
            '[头像]'=> $user['head_pic']?:$domain_url.'/static/img/touxiang.png',
            '[昵称]'=> $user['nickname'],
            '[姓名]'=> $user['nickname'],
            '[手机号]'=> $user['mobile'],
            '[商城名称]'=> tpCache('basic.store_name'),
            '[商品名称]'=>$product['goods_name'],
            '[商品销售价]'=>$product['shop_price'],
            '[商品市场价]'=>$product['market_price'],
            '[商品图片]'=>$product['original_img'],
        ];
        $poster = $this->_getposter(1,$platform,$posterset['content'],$page,$scene,$textReplaceArr);
        $posterdata = [];
        $posterdata['aid'] = 1;
        $posterdata['user_id'] = $this->user_id;
        $posterdata['scene'] = $scene;
        $posterdata['page'] = $page;
        $posterdata['type'] = 'product';
        $posterdata['poster'] = $poster;
        $posterdata['posterid'] = $poster_id;
        $posterdata['createtime'] = time();

        return ['status'=>1,'poster'=>$posterdata['poster']];
    }

    //生成海报
    function _getposter($aid,$platform,$posterdata,$page,$scene,$textReplaceArr){
        set_time_limit(0);
        $domain = getCurUrl();

        $posterdata = json_decode($posterdata,true);
        $poster_bg = $posterdata['poster_bg'];
        $poster_data = $posterdata['poster_data'];
        @ini_set('memory_limit', -1);

//        if($poster_bg){
//            if(strpos($poster_bg,'http') ===false){
//                $poster_bg = getCurUrl().$poster_bg;
//            }
//            $bg = imagecreatefromstring(curlGet($poster_bg));
//            $bgwidth = imagesx($bg);
//            $bgheight = imagesy($bg);
//            if($bgheight/$bgwidth > 1.92) $bgheight = floor($bgwidth * 1.92);
//            $target = imagecreatetruecolor($bgwidth, $bgheight);
//            imagecopy($target, $bg, 0, 0, 0, 0,$bgwidth,$bgheight);
//            imagedestroy($bg);
//        }else{
            $bgwidth = 680;
            $bgheight = 1080;
            $target = imagecreatetruecolor(680, 1080);
            imagefill($target,0,0,imagecolorallocate($target, 255, 255, 255));
//        }
        $huansuan = $bgwidth/340;
        //$bgwidth = imagesx($bg);
        //$bgheight = imagesy($bg);


        $font = ROOT_PATH."static/fonts/msyh.ttf";
        foreach ($poster_data as $d){

            $d['left'] = intval(str_replace('px', '', $d['left'])) * $huansuan;
            $d['top'] = intval(str_replace('px', '', $d['top'])) * $huansuan;
            $d['width'] = intval(str_replace('px', '', $d['width'])) * $huansuan;
            $d['height'] = intval(str_replace('px', '', $d['height'])) * $huansuan;
            $d['size'] = intval(str_replace('px', '', $d['size'])) * $huansuan/2*1.5;

            if ($d['type'] == 'qrwx'){
                $url = 'https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token='.\app\common\Wechat::access_token($aid,'wx');
                $data = array();
                $data['scene'] = $scene;
                $data['page'] = ltrim($page,'/');
                $res = request_post($url,jsonEncode($data));
                $errmsg =json_decode($res,true);
                if($errmsg){
                    if($errmsg['errcode'] == 41030){
                        echojson(array('status'=>0,'msg'=>'小程序发布后才能生成分享海报'));
                    }else{
                        echojson(array('status'=>0,'msg'=>$errmsg['errmsg']));
                    }
                }
                //$filepath = '/upload/poster/'.$aid.'/'.date('Ym/d').'/'.date('His').rand(1000,9999).'.jpg';
                //mk_dir(dirname(ROOT_PATH.ltrim($filepath,'/')));
                //file_put_contents(ROOT_PATH.ltrim($filepath,'/'),$res);
                //$qrcode = PRE_URL.$filepath;
                //$img = imagecreatefromstring(request_get($qrcode));
                if(!$errmsg){
                    $img = imagecreatefromstring($res);
                    imagecopyresampled($target, $img, $d['left'], $d['top'], 0, 0, $d['width'], $d['height'],imagesx($img), imagesy($img));
                }else{
                    //echojson(array('status'=>0,'msg'=>$errmsg['errmsg']));
                }
            } else if ($d['type'] == 'qrmp') {
                $qrcode = createqrcode($domain .'/h5/index.html#'.$page.'?scene='.$scene.'&t='.time());
                $img = imagecreatefromstring(request_get($qrcode));
                imagecopyresampled($target, $img, $d['left'], $d['top'], 0, 0, $d['width'], $d['height'],imagesx($img), imagesy($img));
            }else if($d['type'] == 'qrgz'){
                $url = 'https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token='.\app\common\Wechat::access_token($aid,'mp');
                $data = array();
                $data['action_name'] = 'QR_LIMIT_STR_SCENE';
                $data['action_info'] = ['scene'=>['scene_str'=>$scene]];
                $rs = request_post($url,jsonEncode($data));
                $rs = json_decode($rs,true);
                if($rs['url']){
                    $qrcode = createqrcode($rs['url']);
                    $img = imagecreatefromstring(request_get($qrcode));
                    imagecopyresampled($target, $img, $d['left'], $d['top'], 0, 0, $d['width'], $d['height'],imagesx($img), imagesy($img));
                }else{
                    //echojson(array('status'=>0,'msg'=>\app\common\Wechat::geterror($rs)));
                }
            }else if ($d['type'] == 'img') {
                if($d['src'][0] == '/') $d['src'] = $domain.$d['src'];
                $img = imagecreatefromstring(request_get($d['src']));
                if($img)
                    imagecopyresampled($target, $img, $d['left'], $d['top'], 0, 0, $d['width'], $d['height'],imagesx($img), imagesy($img));
            } else if ($d['type'] == 'text') {
                $d['content'] = str_replace(array_keys($textReplaceArr),array_values($textReplaceArr),$d['content']);
                $colors = hex2rgb2($d['color']);
                $color = imagecolorallocate($target, $colors['red'], $colors['green'], $colors['blue']);
                imagettftext($target, $d['size'], 0, $d['left'], $d['top'] + $d['size'], $color, $font,  $d['content']);
            } else if ($d['type'] == 'textarea') {
                $d['content'] = str_replace(array_keys($textReplaceArr),array_values($textReplaceArr),$d['content']);
                $colors = hex2rgb2($d['color']);
                $color = imagecolorallocate($target, $colors['red'], $colors['green'], $colors['blue']);
                $string = $d['content'];
                $_string='';
                $__string='';
                $_height = 0;
                mb_internal_encoding("UTF-8"); // 设置编码
                for($i=0;$i<mb_strlen($string);$i++){
                    $box = imagettfbbox($d['size'],0,$font,$_string);
                    $_string_length = $box[2]-$box[0];
                    $box = imagettfbbox($d['size'],0,$font,mb_substr($string,$i,1));
                    if($_string_length+$box[2]-$box[0]<$d['width']*1){
                        $_string.=mb_substr($string,$i,1);
                    }else{
                        $_height += $box[1]-$box[7]+4;
                        //var_dump($_height.'--'.$d['height']);
                        if($_height >= $d['height']*1){
                            break;
                        }
                        $__string.=$_string."\n";
                        $_string=mb_substr($string,$i,1);
                    }
                }
                $__string.=$_string;
                $box=imagettfbbox($d['size'],0,$font,mb_substr($__string,0,1));
                imagettftext($target,$d['size'],0,$d['left'],$d['top']+($box[3]-$box[7]),$color,$font,$__string);

            } else if ($d['type'] == 'pro_img') {
                $img = imagecreatefromstring(request_get($textReplaceArr['[商品图片]']));
                if($img)
                    imagecopyresampled($target, $img, $d['left'], $d['top'], 0, 0, $d['width'], $d['height'],imagesx($img), imagesy($img));
            } else if ($d['type'] == 'shadow') {
                $rgba = explode(',',str_replace(array(' ','(',')','rgba'),'',$d['shadow']));
                //dump($rgba);
                $black = imagecreatetruecolor($d['width'], $d['height']);
                imagealphablending($black, false);
                imagesavealpha($black, true);
                $blackcolor = imagecolorallocatealpha($black,$rgba[0],$rgba[1],$rgba[2],(1-$rgba[3])*127);
                imagefill($black, 0, 0, $blackcolor);
                imagecopy($target, $black, $d['left'], $d['top'], 0, 0, $d['width'], $d['height']);
                imagedestroy($black);
            } else if($d['type'] == 'head') {
                $src_img = imagecreatefromstring(request_get($textReplaceArr['[头像]']));
                if($src_img){
                    $w = imagesx($src_img);
                    $h = imagesy($src_img);
                    $radius = $d['radius']*0.01*$w/2;
                    if($radius > 0){
                        $img = imagecreatetruecolor($w, $h);
                        //这一句一定要有
                        imagesavealpha($img, true);
                        //拾取一个完全透明的颜色,最后一个参数127为全透明
                        $bg = imagecolorallocatealpha($img, 255, 255, 255, 127);
                        imagefill($img, 0, 0, $bg);
                        $r = $radius; //圆 角半径
                        for ($x = 0; $x < $w; $x++) {
                            for ($y = 0; $y < $h; $y++) {
                                $rgbColor = imagecolorat($src_img, $x, $y);
                                if (($x >= $radius && $x <= ($w - $radius)) || ($y >= $radius && $y <= ($h - $radius))) {
                                    //不在四角的范围内,直接画
                                    imagesetpixel($img, $x, $y, $rgbColor);
                                } else {
                                    //在四角的范围内选择画
                                    //上左
                                    $y_x = $r; //圆心X坐标
                                    $y_y = $r; //圆心Y坐标
                                    if (((($x - $y_x) * ($x - $y_x) + ($y - $y_y) * ($y - $y_y)) <= ($r * $r))) {
                                        imagesetpixel($img, $x, $y, $rgbColor);
                                    }
                                    //上右
                                    $y_x = $w - $r; //圆心X坐标
                                    $y_y = $r; //圆心Y坐标
                                    if (((($x - $y_x) * ($x - $y_x) + ($y - $y_y) * ($y - $y_y)) <= ($r * $r))) {
                                        imagesetpixel($img, $x, $y, $rgbColor);
                                    }
                                    //下左
                                    $y_x = $r; //圆心X坐标
                                    $y_y = $h - $r; //圆心Y坐标
                                    if (((($x - $y_x) * ($x - $y_x) + ($y - $y_y) * ($y - $y_y)) <= ($r * $r))) {
                                        imagesetpixel($img, $x, $y, $rgbColor);
                                    }
                                    //下右
                                    $y_x = $w - $r; //圆心X坐标
                                    $y_y = $h - $r; //圆心Y坐标
                                    if (((($x - $y_x) * ($x - $y_x) + ($y - $y_y) * ($y - $y_y)) <= ($r * $r))) {
                                        imagesetpixel($img, $x, $y, $rgbColor);
                                    }
                                }
                            }
                        }
                        imagecopyresampled($target, $img, $d['left'], $d['top'], 0, 0, $d['width'], $d['height'],imagesx($img), imagesy($img));
                    }else{
                        imagecopyresampled($target, $src_img, $d['left'], $d['top'], 0, 0, $d['width'], $d['height'],imagesx($src_img), imagesy($src_img));
                    }
                }
            }
        }
        $url = '/upload/'.date('Ym/d_His').rand(1000,9999).'.jpg';
        $filepath = ROOT_PATH.ltrim($url,'/');
        if(!file_exists(dirname($filepath))){
            mkdir(dirname($filepath),0775,true);
        }
        imagejpeg($target,$filepath,100);
        return $domain.$url;
    }

    //获取促销信息
    public function getcuxiaoinfo(){
        $id = input('post.id');
        $info = Db::name('cuxiao')->where('id',$id)->find();
        if(!$info){
            return $this->json(['status'=>0,'msg'=>'获取失败']);
        }
        $proinfo = false;
        $gginfo = false;
        if(($info['type'] == 2 || $info['type'] == 3) && $info['proid']){
            $proinfo = Db::name('goods')->field('id,name,pic,shop_price')->where('goods_id',$info['proid'])->find();
            $gginfo = Db::name('spec_goods_price')->where('id',$info['ggid'])->find();
        }
        return ['status'=>1,'info'=>$info,'product'=>$proinfo,'guige'=>$gginfo];

    }
}
